$(document).ready(function(){
	$("#btnFilter").click(function(){
		filterGradeBySelectedOption();
	});
	$("#bthAdd").click(function(){
		popupAddDialog();
	});

	filterGradeBySelectedOption();
	
	initDialog();
});

function filterGradeBySelectedOption() {
	filterGrade($("#selectActive").val());
}

function initDialog() {
	// 初始化弹出表单中的学习阶段可选项
    $.ajax({
        type: "GET",
        url: "../public/education-stages",
        dataType: "json",
        success: function (resp) {
            if (resp.code == "0") {
                var stageSelectObj = $("#gradeDialog #stage");
                $.each(resp.data,function(index, item) {
                	var optionHtml = "<option value='" + item.code + "'>" + item.name + "</option>";
                	stageSelectObj.append(optionHtml);
                });
            } else {
                alert("服务器返回出错信息：\n\n" + resp.message);
            }
        },
        error: function () { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });
}

function filterGrade(active) {
	$("#txtMessage").text("页面正在加载...")
	var url = location.href + "/..";
    $.ajax({
        type: "GET",
        url: url,
        data: {active: active},
        dataType: "json",
        success: function (resp) {
            if (resp.code == "0") {
                var tableBodyObj = $("#tableGrades tbody");
                tableBodyObj.html("");
                $.each(resp.data,function(index, item) {
                	var rowHtml = "<tr dataStr=" + JSON.stringify(item) + ">";
                	rowHtml += "<td>" + item.id + "</td>";
                	rowHtml += "<td>" + item.name + "</td>";
                	rowHtml += "<td>" + item.stage + "</td>";
                	rowHtml += "<td>" + item.graduateGrade + "</td>";
                	rowHtml += "<td>" + item.nextGradeName + "</td>";
                	rowHtml += "<td>" + item.code + "</td>";
                	rowHtml += "<td>" + item.active + "</td>";
                	rowHtml += "<td><span class='clickable' onclick='popupEditDialog(event)'>edit</span></td>";
                	rowHtml += "</tr>";
                	tableBodyObj.append(rowHtml);
                });
                
                var countSummaryObj = $("#txtCountSummary");
                countSummaryObj.html("共 " + resp.data.length + " 条记录");
                
            } else {
                alert("服务器返回出错信息：\n\n" + resp.message);
            }
        	$("#txtMessage").text("");
        },
        error: function () { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });
}

var gradeDialog = $("#gradeDialog").dialog({
    autoOpen: false,
    height:300,
    width: 300,
    modal: true,
	close: function() {}
});

function popupAddDialog() {
    $("#gradeDialog #id").val("");
    $("#gradeDialog #name").val("");
    $("#gradeDialog #code").val("");
    $("#gradeDialog #graduateGrade").removeAttr("checked");
	initNextGradeSelection();
    $("#gradeDialog input[name='active'][value='true']").get(0).checked = true;
    
	gradeDialog = gradeDialog.dialog({
		label: "增加新的年级",
	    buttons: {
	    	"添加新年级": addGrade,
	    	Cancel: function() {
	    		gradeDialog.dialog("close");
	    	}
	    }
	});
	gradeDialog.dialog("open");
}

function addGrade() {
	var name = $("#gradeDialog #name").val();
	var stage =  $("#gradeDialog #stage").val();
	var graduateGrade = $("#gradeDialog #graduateGrade").checked;
	var nextGradeId = $("#gradeDialog #nextGrade").val();
	var code =  $("#gradeDialog #code").val();
	var active = $("#gradeDialog input[name='active']:checked").val();
	var postData = {name:name, stage:stage, graduateGrade:graduateGrade, nextGradeId:nextGradeId, code:code, active:active};
	var url = location.href + "/..";
    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(postData),
        dataType: "json",
        contentType:"application/json",
        success: function (resp) {
            if (resp.code == "0") {
            	gradeDialog.dialog("close");
            	filterGrade(); // 刷新页面
                
            } else {
            	alert("服务器返回出错信息：\n\n" + resp.message);
            }
        },
        error: function() { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });    
}

function popupEditDialog(event) {
	event = event || window.event;
    var sourceObj = event.srcElement || event.target;
    var trObject = $(sourceObj).closest("tr");
    var item = JSON.parse(trObject.attr("dataStr"));
    $("#gradeDialog #id").val(item.id);
    $("#gradeDialog #name").val(item.name);
    $("#gradeDialog #stage").val(item.stage);
	$("#gradeDialog #graduateGrade").prop("checked",item.graduateGrade)

	initNextGradeSelection(item.nextGradeId);
	$("#gradeDialog #code").val(item.code);
    var radioSelectorStr = "#gradeDialog input[name='active'][value='" + item.active + "']";
    $(radioSelectorStr).get(0).checked = true;
    
	gradeDialog = gradeDialog.dialog({
		label: "修改年级设置",
	    buttons: {
	    	"保存修改内容": updateGrade,
	    	Cancel: function() {
	    		gradeDialog.dialog("close");
	    	}
	    }
	});
	gradeDialog.dialog("open");
}

function initNextGradeSelection(nextGradeId) {
	var url = location.pathname + "/.."
	debugger;
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        success: function (resp) {
            if (resp.code == "0") {
                var nextGradeSelectObj = $("#gradeDialog #nextGrade");
                nextGradeSelectObj.empty();
                $.each(resp.data,function(index, item) {
                	var optionHtml = "<option value='" + item.id + "'>" + item.name + "</option>";
                	nextGradeSelectObj.append(optionHtml);
                });
                nextGradeSelectObj.val(nextGradeId);
                
            } else {
                alert("服务器返回出错信息：\n\n" + resp.message);
            }
        },
        error: function () { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });
}

function updateGrade() {
	var id = $("#gradeDialog #id").val();
	var name = $("#gradeDialog #name").val();
	var stage =  $("#gradeDialog #stage").val();
	var graduateGrade = $("#gradeDialog #graduateGrade").is(":checked");
	var code = $("#gradeDialog #code").val();
	var nextGradeId = $("#gradeDialog #nextGrade").val();
	var active = $("#gradeDialog input[name='active']:checked").val();
	debugger
	var postData = {id:id, name:name, stage:stage, graduateGrade:graduateGrade, code:code, nextGradeId:nextGradeId, active:active};
    $.ajax({
        type: "POST",
        url: id,
        data: JSON.stringify(postData),
        dataType: "json",
        contentType:"application/json",
        success: function (resp) {
            if (resp.code == "0") {
            	gradeDialog.dialog("close");
            	filterGrade(); // 刷新页面
            } else {
            	alert("服务器返回出错信息：\n\n" + resp.message);
            }
        },
        error: function () { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });
}
